package util

import (
	"context"
	"fmt"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"strconv"
	"time"
)

func GetPostUniqueId(ctx context.Context, uid uint64) (uint64, error) {
	return GetUniqueId(ctx, uid, "post_id")
}

func GetCommentUniqueId(ctx context.Context, uid uint64) (uint64, error) {
	return GetUniqueId(ctx, uid, "comment_id")
}

func GetCommentReplyUniqueId(ctx context.Context, uid uint64) (uint64, error) {
	return GetUniqueId(ctx, uid, "comment_id")
}

func GetUniqueId(ctx context.Context, uid uint64, keyPrefix string) (uint64, error) {
	base := 1430409600
	now := int(time.Now().Unix())
	key := fmt.Sprint("%v_%v", keyPrefix, now)

	incrId, err := baseStore.GetRedisStore().IncrBy(ctx, key, 1).Result()
	if err != nil {
		baseLog.Errorf("GetPostOrCommentUniqueId incrby err:%v", err)
		return 0, err
	}
	_, err = baseStore.GetRedisStore().Expire(ctx, key, 2*time.Second).Result()
	if err != nil {
		baseLog.Errorf("GetPostOrCommentUniqueId expire err:%v", err)
		return 0, err
	}

	value := fmt.Sprintf("%d%06d%04d", now-base, incrId%1000000, uid%10000)
	uniqueId, err := strconv.ParseUint(value, 10, 64)
	if err != nil {
		baseLog.Errorf("GetPostOrCommentUniqueId ParseInt err:%v", err)
		return 0, err
	}
	return uniqueId, nil
}

func GetProductId(ctx context.Context) (int64, error) {
	nowTime := time.Now()
	key := fmt.Sprintf("%v_%v", "product_id", nowTime.Unix())
	incrId, err := baseStore.GetRedisStore().IncrBy(ctx, key, 1).Result()
	if err != nil {
		return 0, err
	}
	_, err = baseStore.GetRedisStore().Expire(ctx, key, 2*time.Second).Result()
	if err != nil {
		return 0, err
	}
	idstring := fmt.Sprintf("%v%v", incrId, nowTime.Unix())
	idint, err := strconv.ParseInt(idstring, 10, 64)
	if err != nil {
		return 0, err
	}
	return idint, err
}
